#include "stdafx.h"
#pragma warning (disable : 4786)
#pragma warning (disable : 4086)

#include "ClientCallbackData.h"
ClientCallbackData::ClientCallbackData()
{
	m_pSocketClient = NULL;
	//m_bConnected = false;
	RegisterHandler(0,boost::bind(&ClientCallbackData::phPing, this,_1));
}
ClientCallbackData::ClientCallbackData(ISocketClient *pSocketClient)
{
	m_pSocketClient = pSocketClient;
	//m_bConnected = false;
}

void ClientCallbackData::OnConnect()
{
	//m_bConnected = true;
}
void ClientCallbackData::OnReconnect()
{
	//m_bConnected = true;
}

void ClientCallbackData::OnRecvData(const void* pData, size_t nDataLen)
{
	PacketDecoder decoder;
	if(decoder.SetData(reinterpret_cast<const char*>(pData), nDataLen + 4) == false)
	{
		LOGGER_ERROR("error :bad request1");
		return;
	}

	if(decoder.GetItemCount() < 2)
	{
		LOGGER_ERROR("error :bad request decoder.GetItemCount() < 2");
		return;
	}

	Int32 type = 0;
	Int32 id = 0;

	if(decoder.GetItem(0, type) == false || decoder.GetItem(1, id) == false)
	{
		LOGGER_ERROR("error :bad request");
		return;
	}

	#ifdef _WIN32
	if(!(type == 0 && id == 0))
		printf("ClientCallbackData OnRecvData type:%d,id:%d\n",type,id);
	#endif

	if(id < 0 || id >= 65536)
	{
		LOGGER_ERROR("error :method id:%d,is out of range",id);
		return;
	}

	PacketHandler method = GetHandler(id);
	if(method == NULL)
	{
		LOGGER_ERROR("error :method id:%d,is unimplement",id);
		return;
	}
	method((void*)(&decoder));
};
void ClientCallbackData::phPing(void *pData)
{
	static PacketEncoder encoder;
	encoder.Clear();
	encoder.AddItem(Int32(0));
	encoder.AddItem(Int32(0));

	void *p = const_cast<void*>(encoder.GetData());
	m_pSocketClient->SendData((char*)p+sizeof(UInt32),encoder.GetDataSize()-sizeof(UInt32));
}
void ClientCallbackData::OnCloseConnection()
{
	//m_bConnected = false;
}
void ClientCallbackData::OnUpdate()
{
}

void ClientCallbackData::SendPacketToData(PacketEncoder& encoder)
{
	void *p = const_cast<void*>(encoder.GetData());
	m_pSocketClient->SendData((char*)p+sizeof(UInt32),encoder.GetDataSize()-sizeof(UInt32));
}

void SendPacketToData(PacketEncoder& encoder)
{
	singleton<ClientCallbackData>::instance().SendPacketToData(encoder);
}

// ISocketClientCallback* CreateClientCallbackData(ISocketClient*pSocketClient)
//{
//	singleton<ClientCallbackData>::instance().setSocketClient(pSocketClient);
//	return &(singleton<ClientCallbackData>::instance());
//}